import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';
import { ConfigService } from './config.service';

@Injectable({
  providedIn: 'root'
})
export class StudentService {

    private baseUrl = this.configService.api.url + '/students';  // URL to web API
    private subject: any = {
        create: new Subject<any>(),
        delete: new Subject<any>(),
        update: new Subject<any>(),
        refresh: new Subject<any>()
    };

    constructor(private http: HttpClient, private configService: ConfigService) {
    }

    on(event, callback) {
        return this.subject[event].subscribe(value => callback(value));
    }

    emit(event, value: any) {
        return this.subject[event].next(value);
    }

    create(student): Observable<any> {
        student._id = this.configService.guid();
        return this.http.post(this.baseUrl + '/create', {student: student});
    }

    delete(id: string): Observable<any> {
        return this.http.post(this.baseUrl + '/' + id + '/remove', {});
    }

    update(student): Observable<any> {
        return this.http.post(this.baseUrl + '/' + student._id + '/update', {student: student});
    }

    getAll(): Observable<any> {
        return this.http.get(this.baseUrl + '/');
    }

    getOne(id: string): Observable<any> {
        return this.http.get(this.baseUrl + '/detail/' + id);
    }

}
